<?php
// 批量处理菜品信息：获取AI信息、更新数据库、标记ai_called字段

require_once '../thinkphp/base.php';

use think\Db;

/**
 * 调用API获取菜品信息
 */
function getDishInfoFromAPI() {
    $url = 'http://localhost/api/food_ingredient/batchGetDishInfo';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $responseData = json_decode($response, true);
    if ($responseData && $responseData['code'] == 1) {
        return $responseData['data'];
    }
    
    return null;
}

/**
 * 更新菜品信息并标记ai_called字段
 */
function updateDishInfo($dishId, $dishInfo) {
    // 开始事务
    Db::startTrans();
    try {
        // 更新菜品信息
        $updateData = [
            'steps' => $dishInfo['steps'] ?? '',
            'cook_time' => $dishInfo['cook_time'] ?? '',
            'updatetime' => time()
        ];
        
        Db::name('food_dish')->where('id', $dishId)->update($updateData);
        
        // 删除原有的食材关联
        Db::name('food_ingredientrel')->where('dish_id', $dishId)->delete();
        
        // 添加新的食材关联
        if (!empty($dishInfo['ingredients'])) {
            $insertData = [];
            foreach ($dishInfo['ingredients'] as $index => $ingredient) {
                if (isset($ingredient['id']) && $ingredient['id'] > 0) {
                    $insertData[] = [
                        'dish_id' => $dishId,
                        'ingredient_id' => intval($ingredient['id']),
                        'quantity' => $ingredient['quantity'] ?? '100g',
                        'createtime' => time(),
                        'weigh' => $index + 1
                    ];
                }
            }
            
            if (!empty($insertData)) {
                Db::name('food_ingredientrel')->insertAll($insertData);
            }
        }
        
        // 标记为已调用AI
        Db::name('food_dish')->where('id', $dishId)->update(['ai_called' => 1]);
        
        // 提交事务
        Db::commit();
        echo "成功更新菜品ID {$dishId}\n";
        return true;
    } catch (\Exception $e) {
        // 回滚事务
        Db::rollback();
        echo "更新菜品ID {$dishId} 失败: " . $e->getMessage() . "\n";
        return false;
    }
}

/**
 * 主处理函数
 */
function processDishes() {
    echo "开始批量处理菜品信息...\n";
    
    // 调用API获取菜品信息
    echo "调用API获取菜品信息...\n";
    $dishInfos = getDishInfoFromAPI();
    
    if (empty($dishInfos)) {
        echo "获取菜品信息失败或没有需要处理的菜品\n";
        return;
    }
    
    echo "成功获取 " . count($dishInfos) . " 个菜品的信息\n";
    
    // 更新每个菜品的信息
    $successCount = 0;
    foreach ($dishInfos as $dishId => $dishInfo) {
        if (updateDishInfo($dishId, $dishInfo)) {
            $successCount++;
        }
    }
    
    echo "处理完成，成功更新 {$successCount} 个菜品\n";
}

// 执行处理
processDishes();
?>